from PyQt4.QtGui import QSyntaxHighlighter
from PyQt4.QtGui import QTextCharFormat
from PyQt4.QtGui import QFont
from PyQt4.QtCore import QRegExp
from PyQt4.QtCore import Qt

class HtmlHighlighter(QSyntaxHighlighter):

    def __init__(self, parent):
        QSyntaxHighlighter.__init__(self, parent)
        self.rules = []
        rule = QTextCharFormat()
        rule.setForeground(Qt.green)
        pattern = QRegExp('(\d)+')
        self.rules.append(HighlightingRule(pattern, rule))
        rule = QTextCharFormat()
        rule.setForeground(Qt.darkBlue)
        rule.setFontWeight(QFont.Bold)
        pattern = QRegExp('<(\s)*((\w)+(\s)*(\w)*([="])*(\s)*(/)?)+>')
        self.rules.append(HighlightingRule(pattern, rule))
        pattern = QRegExp('</(\s)*(\w)+(\s)*>')
        self.rules.append(HighlightingRule(pattern, rule))
        rule = QTextCharFormat()
        rule.setForeground(Qt.darkCyan)
        rule.setFontWeight(QFont.Bold)
        pattern = QRegExp('(\w)+="')
        self.rules.append(HighlightingRule(pattern, rule))
        rule = QTextCharFormat()
        rule.setForeground(Qt.magenta)
        pattern = QRegExp('"((\w)+(\s)*[!#$%&/()=?@]*)+"')
        self.rules.append(HighlightingRule(pattern, rule))
        """rule = QTextCharFormat()
        rule.setFontItalic(True)
        rule.setForeground(Qt.darkMagenta)
        pattern = QRegExp('(<script>)+(\w)+(</script>)+')
        self.rules.append(HighlightingRule(pattern, rule))"""

    def highlightBlock(self, text):
        for rule in self.rules:
            expression = QRegExp(rule.pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, rule.format)
                index = text.indexOf(expression, index + length)


class HighlightingRule(object):

    def __init__(self, pattern, format):
        self.pattern = pattern
        self.format = format
